package com.wyj.chat.websocket_chat.controller;

import com.wyj.chat.websocket_chat.pojo.Group;
import com.wyj.chat.websocket_chat.utils.GroupMsg;
import com.wyj.chat.websocket_chat.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Create by wyj on 2018/4/18
 */
@RestController
public class GroupController {

    @Autowired
    private GroupService groupService;

    /**
     * 搜索群名
     * @param groupName
     * @return
     */
    @RequestMapping(value = "/group/searchGroupByName", method = RequestMethod.POST)
    @ResponseBody
    public GroupMsg searchGroupByName(String groupName) {
        if(StringUtils.isEmpty(groupName))
            return null;

        Group group = groupService.searchGroupByName(groupName);
        GroupMsg groupMsg = new GroupMsg();
        if(group != null) {
            groupMsg.setState("success");
            groupMsg.setGroup(group);
            return groupMsg;
        }else {
            groupMsg.setState("error");
            groupMsg.setGroup(null);
            return groupMsg;
        }
    }

    /**
     * 加群
     * @param groupName
     * @return
     */
    @RequestMapping(value = "/group/addGroup", method = RequestMethod.POST)
    @ResponseBody
    public boolean addGroup(String groupName,String name) {
        if(StringUtils.isEmpty(groupName) || StringUtils.isEmpty(name))
            return false;

        int exitInGroup = groupService.isExitInGroup(groupName, name);
        if(exitInGroup == 1)
            return false;// 已经是群成员

        int result = groupService.addGroup(groupName,name);
        if(result == 1)
            return true;// 加群成功
        return false;
    }

    /**
     * 获取已加入的群组列表
     * @param name
     * @return
     */
    @RequestMapping(value = "/group/getGroupList", method = RequestMethod.POST)
    @ResponseBody
    public List<String> getGroupList(String name) {
        List<String> groupList = groupService.getGroupNameList(name);
        if (groupList != null) {
            return groupList;
        }
        return null;
    }

    /**
     * 获取群成员
     * @param groupName
     * @return
     */
    @RequestMapping(value = "/group/getMemberList", method = RequestMethod.POST)
    @ResponseBody
    public List<String> getMemberList(String groupName) {
        if(StringUtils.isEmpty(groupName))
            return null;

        List<String> memberList = groupService.getMemberList(groupName);
        if(memberList != null) {
            return memberList;
        }
        return null;
    }
}
